<template>
  <div class="c-image" :style="[style]">
		<view class="image-loading" v-if="loading">
			<u-loading-icon mode="circle" size="28" duration="1500" v-if="loadingIcon == 'icon'"/>
			<image :src="loadingIcon" mode="aspectFit" v-else />
		</view>
   <image src="/static/images/def-img.png" mode="aspectFit" v-else-if="error"/>
		<template v-if="preview">
			<image :src="src" :mode="mode" :lazy-load="lazyLoad" v-show="!loading && !error"
				@click.stop="onPreview"
				@error="errorHandler"
				@load="handleLoad"/>
		</template>
		<template v-else>
			<image :src="src" :mode="mode" :lazy-load="lazyLoad" v-show="!loading && !error"
				@error="errorHandler"
				@load="handleLoad"/>
		</template>
  </div>
</template>
<script>
export default {
  name: "c-image",
  props: {
    src: {
      type: String,
    },
    mode: {
      type: String,
      default: "scaleToFill"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
		radius: {
			type: String,
			default: "0"
		},
		loadingIcon: {
			type: String,
			default: '/static/images/def-img.png'
		},
    lazyLoad: {
      type: Boolean,
      default: true
    },
		preview: {
			type: Boolean,
			default: false
		},
		urls: {
			type: Array,
			default: () => []
		}
  },
  data() {
    return {
      loading: true,
      error: false
    }
  },
  computed: {
    style() {
      return {
        width: this.width,
        height: this.height,
				borderRadius: this.radius
      }
    }
  },
  methods: {
    handleLoad() {
      this.loading = false
    },
    errorHandler() {
			this.loading = false
      this.error = true
    },
		onPreview() {
			let index = 0, urls = [this.src]
			if (this.urls.length) {
				index = this.urls.findIndex(u => u == this.src)
				urls = this.urls
			}
			uni.previewImage({
				urls: urls,
				current: index
			})
		},
  },
  created() {
		this.loading = true
  },
  watch: {},
	options: {
		virtualHost: true
	}
}
</script>

<style scoped lang="scss">
.c-image {
  width: 100%;
  height: 100%;
  overflow: hidden;
	.image-loading {
		width: 100%;
		height: 100%;
		font-size: 24rpx;
		color: #808080;
		display: flex;
		align-items: center;
		justify-content: center;
	}
  image {
    width: 100%;
    height: 100%;
  }
}
</style>
